package A1_二叉树;

public class LC_112路径总和 {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val=val;
        }
        TreeNode(int val, TreeNode left, TreeNode right){
            this.val=val;
            this.left=left;
            this.right=right;
        }
    }
    public static void main(String[] args){
//        TreeNode node=new TreeNode(1);
        TreeNode node=new TreeNode(5);
        node.left=new TreeNode(4);
        node.right=new TreeNode(8);
        node.left.left=new TreeNode(11);
        node.right.left=new TreeNode(13);
        node.right.right=new TreeNode(4);
        node.left.left.left=new TreeNode(7);
        node.left.left.right=new TreeNode(2);
        node.right.right.left=new TreeNode(5);
        node.right.right.right=new TreeNode(1);
        System.out.println(hasPathSum(node,22));
    }
    public static boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null)
            return false;
//        if(root.right==null && root.left==null && targetSum==root.val)
//            return true;
        targetSum-=root.val;
        if(root.left==null && root.right==null && targetSum==0)
            return true;
        if(root.left==null && root.right==null && targetSum!=0)
            return false;
        if(root.left!=null){
//            targetSum-=root.left.val;
            if(hasPathSum(root.left,targetSum))
                return true;
//            targetSum+=root.left.val;//回溯
        }
        if(root.right!=null){
//            targetSum-=root.right.val;
            if(hasPathSum(root.right,targetSum))
                return true;
//            targetSum+=root.right.val;
        }
        return false;
    }
}
